package org.theSeed.base.pojo.dto;

import cn.hutool.core.lang.UUID;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.theSeed.base.pojo.config.NameThreadFactory;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;

@Slf4j
public class ForkJoinDto {
    public ForkJoinDto() {
        this.handler = (ele,exp)->{
            log.error(ele.getName()+"线程异常",exp);
        };
        this.saturate = pool->{
            log.warn("线程池已饱和,当前数量为{}",pool.getPoolSize());
            return false;
        };
    }

    /**
     * 线程池名称
     */
    @Getter
    @Setter
    private String poolName = UUID.randomUUID().toString();

    /**
     * 并行级别
     */
    @Getter
    @Setter
    private int parallelism = Runtime.getRuntime().availableProcessors();

    /**
     * 异步模式
     * false（默认）：后进先出（LIFO）调度，适合计算密集型任务
     * true：先进先出（FIFO）调度，适合事件驱动型任务
     */
    @Getter
    @Setter
    private Boolean asyncMode = false;

    /**
     * 核心线程数
     */
    @Getter
    @Setter
    private int corePoolSize = Runtime.getRuntime().availableProcessors();

    /**
     * 最大线程数
     */
    @Getter
    @Setter
    private int maximumPoolSize = Double.valueOf(Math.floor(Runtime.getRuntime().availableProcessors() * 1.5)).intValue();

    /**
     * 最小可运行线程数
     */
    @Getter
    @Setter
    private int minimumRunnable = 2;

    /**
     * 空闲线程存活时间秒
     */
    @Getter
    @Setter
    private long keepAliveTime = 10 * 60;


    /**
     * 饱和策略
     */
    @Getter
    @Setter
    private Predicate<? super ForkJoinPool> saturate;

    /**
     * 异常处理器
     */
    @Getter
    @Setter
    private Thread.UncaughtExceptionHandler handler;

    /**
     * 创建池
     * @return
     */
    public ForkJoinPool createForkJoinPool(){
        return new ForkJoinPool(parallelism, NameThreadFactory.getDefaultThreadFactory(),handler,asyncMode,corePoolSize,maximumPoolSize,minimumRunnable,saturate,keepAliveTime, TimeUnit.SECONDS);
    }
}
